let db = require("../../../db/db")
let rights_handler = require("../../rights_handler")
let process_handler = require("./process_handler")


let handle = async function (action, data, login_info, req, res) {
	switch (action) {
		case "approve":
			{
				let process_id = data.process_id;
				let process_def_id = data.process_def_id;
				let f_deployment_id = data.f_deployment_id;
				let f_process_def_id = data.f_process_def_id;
				let title = data.title;
				let comment = data.comment;
				if (!process_id) { //新流程
					let trans = await db.transaction();
					try {
						//添加form记录				
						let datamodel = data.datamodel;
						let tablename = data.tablename;
						let row = data.row;
						sql = "insert into " + db.escapeId(tablename) + " set ?";
						let r = await trans.add(sql, row);
						let form_id = r.results.insertId;
						//添加流程实例
						sql = "insert into bpm_process set ?";
						let params = {
							name: title,
							def_id: process_def_id,
							starter_emp: login_info.emp_id,
							starter_user: login_info.user_id,
							starter_org: login_info.org_id,
							starter_emp_name: login_info.emp_name,
							starter_user_name: login_info.username,
							starter_org_name: login_info.org_name,
							starter_job_number: login_info.job_number,
							starter_position_name: login_info.position_name,
							config: data.config,
							diagram: data.diagram,
							publish: data.publish,
							version: data.version,
							comment: comment,
							form_id: form_id,
							status: "正常",
							create_user: login_info.user_id
						}
						r = await trans.add(sql, params);
						let process_id = r.results.insertId;
						//刷新流程审批候选人
						let variables = await build_candidate_variables(process_id);
						//flowable发起流程
						params = {
							f_deployment_id: f_deployment_id,
							f_process_def_id: f_process_def_id,
							name: title,
							variables: variables
						}
						result = await process_handler.start_a_process(params, login_info);
						let f_process_id = result.id;
						//更新流程实例的f_process_id
						sql = "update bpm_process set f_process_id=? where id=?";
						await trans.update(sql, [f_process_id, process_id]);						
						//刷新待办人
						await refresh_todo({process_id,f_process_id,process_def_id,name:title});
						//TODO:新发起流程，后续任务为发起人的，需自动审批


						//提交全部事务
						await trans.commit();
						return "ok";
					}
					catch (err) {
						trans.rollback();
						throw (err);
					}
				}
				else{ //非新流程
					return (Error('TODO'));
				}
			}
			break;
		default:
			return (Error('未知的action:' + action));
	}
}

//刷新候选人，确定未审批任务的候选人是哪些人，可以确定的确定，不确定的等后续审批再刷新
//方法中需要通过前面节点审批人确定审批人，先存数据库再调用本方法，放到数据库事务中
let build_candidate_variables = async function (process_id) {
	let variables = [];
	//查此流程
	let sql = "select * from bpm_process where id=?";
	let result = await db.query(sql, [process_id]);
	//console.log(result);
	let row = result.rows[0];
	let id = row.id;
	let def_id = row.def_id;
	let starter_emp = row.starter_emp;
	let form_id = row.form_id;
	let config = JSON.parse(row.config);
	let configer = config.process_config.configer;
	let tasks = configer.filter(e => e.type == "bpmn:UserTask");
	for (let task of tasks) {
		//console.log(task);
		let diagram_task_id = task.id;
		let approvers = task.approvers;
		//审批候选人
		let candidates = [];
		for (let approver of approvers) {
			if (approver.type == "employee") {
				if (approver.source == "employee") {
					candidates.push(approver.employee);
				}
				else if (approver.source == "starter") {
					candidates.push(starter_emp);
				}
				else { //TODO：other situations
	
				}
			}
			else if (approver.type == "by_relation") { //TODO
				if (approver.source == "employee") {
					
				}
				else if (approver.source == "starter") {
					
				}
				else { 
	
				}
			}
		}
		variables.push({
			"name": "candidateUsers_" + diagram_task_id,
			"value": candidates.join(",")
		});
	}
	return variables;
}
//从flowable刷新待办人(候选人) 从flowable获取流程的当前任务
let refresh_todo = async function (data) {
	let name = data.name;
	let process_id = data.process_id;
	let process_def_id = data.process_def_id;
	let f_process_id = data.f_process_id;
	let result = await process_handler.query_tasks({f_process_id});
	let sql="";
	let params=[];
	let tasks = result.data;
	let emp_names=[];
	for(let t of tasks){
		let diagram_task_id=t.taskDefinitionKey;
		let variables=t.variables;
		let find=variables.filter(v=>v.name=="candidateUsers_"+diagram_task_id);
		if(find.length==0){
			continue;
		}
		let emps=find[0].value.split(",");
		for(let emp of emps){
			if(!emp){
				continue;
			}
			let s ="select name from ehr_employee where id=?";
			let r = await db.query(s,[emp]);
			if(r.rows.length>0){
				emp_names.push(r.rows[0].name);
			}
			s ="select count(*) as ct from bpm_process_todo where process_id=?"+
				" and todo_emp_id=?"+
				" and status=?"+
				" and diagram_task_id=?";
			r = await db.query(s,[process_id,emp,'待办',diagram_task_id]);
			if(r.rows[0].ct>0){
				continue;
			}
			params.push({
				name: name,
				process_def_id: process_def_id,
				process_id: process_id,
				todo_emp_id: emp,
				status: "待办",
				diagram_task_id: diagram_task_id
			})
			sql+="insert into bpm_process_todo set ? ; ";
		}
	}
	if(sql.length>0){
		db.multiadd(sql,params);
	}
	//更新流程待办人姓名
	let s="update bpm_process set current_approvers=? where id=?";
	db.update(s,[emp_names.join(","),process_id]);
}
//刷新所有待办人，用于定时任务
let refresh_all_todo = async function () {
	//查运行的流程
	let sql = "select * from bpm_process where status='正常' and is_deleted=0";
	let result = await db.query(sql, []);
	for(let row of result.rows){
		let name = row.name;
		let process_id = row.id;
		let process_def_id = row.def_id;
		let f_process_id = row.f_process_id;
		refresh_todo({ name,process_id,process_def_id,f_process_id });
	}
}

module.exports = { handle, refresh_all_todo };